package org.jiucheng.magpiebridge.server.aio.proxy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ClientWriteAttachment;
import org.jiucheng.magpiebridge.server.aio.ClientWriteCompletionHandler;

public class ProxyClientCompletionHandler implements CompletionHandler<Integer, ClientWriteAttachment> {
    
    public void completed(Integer result, ClientWriteAttachment attachment) {
        if (result == -1) {
            try {
                attachment.getProxyAsynchronousSocketChannel().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            Message proxym = new Message();
            proxym.setMagic(Message.MAGIC);
            proxym.setType(Message.Type.DISCONNECT);
            proxym.setUri(attachment.getUri());
            ByteBuffer writeBuffer = Message.toByteBuffer(proxym);
            while (!attachment.getProxyAttachment().getClientAttachment().writed.compareAndSet(false, true)) {}
            attachment.getProxyAttachment().getClientAttachment().getAsynchronousSocketChannel().write(writeBuffer, attachment.setWriteBuffer(writeBuffer).setProxyAsynchronousSocketChannel(null), new ClientWriteCompletionHandler());
            return;
        }
        ByteBuffer readByteBuffer = attachment.getReadByteBuffer();
        readByteBuffer.flip();
        
        Message message = new Message();
        message.setType(Message.Type.TRANSFER);
        message.setUri(attachment.getUri());
        byte[] bts = new byte[result];
        readByteBuffer.get(bts);
        message.setData(bts);
        message.setSize(bts.length);
        
        ByteBuffer writeBuffer = Message.toByteBuffer(message);
        while (!attachment.getProxyAttachment().getClientAttachment().writed.compareAndSet(false, true)) {}
        attachment.getProxyAttachment().getClientAttachment().getAsynchronousSocketChannel().write(writeBuffer, attachment.setWriteBuffer(writeBuffer), new ClientWriteCompletionHandler());
        return;
    }
    
    public void failed(Throwable exc, ClientWriteAttachment attachment) {
        exc.printStackTrace();
    }
}
